/*
Copyright [2020] [https://www.stylefeng.cn]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Guns采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点，可申请商业授权，获取Guns商业授权许可，请在官网购买授权，地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.sys.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.core.annotion.ApiVersion;
import cn.stylefeng.guns.sys.core.enums.SwaggerGroupInterface;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.base.Optional;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;
import java.util.List;

/**
 * swagger配置
 *
 * @author xuyuxiang
 * @date 2020/3/11 15:05
 */
@Configuration("swaggerConfig")
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig implements InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private SwaggerGroupInterface swaggerGroupInterface;

    @Bean
    public Docket createRestApi() {
        Parameter parameter = new ParameterBuilder()
                .name("Authorization")
                .description("token令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();

        List<Parameter> parameters = CollectionUtil.newArrayList();
        parameters.add(parameter);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameters);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Guns Doc")
                .description("Guns Doc文档")
                .termsOfServiceUrl("https://www.stylefeng.cn")
                .contact(new Contact("stylefeng", "https://www.stylefeng.cn", ""))
                .version("1.0")
                .build();
    }

    /**
     * 该方法会在afterPropertiesSet中被注册成工厂方法，进行调用
     *
     * @param groupName
     * @return
     */
    private Docket buildDocket(String groupName) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName(groupName)
                .select()
                .apis(method -> {
                    // 每个方法会进入这里进行判断并归类到不同分组，**请不要调换下面两段代码的顺序，在方法上的注解有优先级**

                    // 该方法上标注了版本
                    if (method.isAnnotatedWith(ApiVersion.class)) {
                        ApiVersion apiVersion = method.findAnnotation(ApiVersion.class).get();
                        if (apiVersion.value() != null && apiVersion.value().length != 0) {
                            if (Arrays.asList(apiVersion.value()).contains(groupName)) {
                                return true;
                            }
                        }

                    }

                    // 方法所在的类是否标注了?
                    Optional<ApiVersion> optional = method.findControllerAnnotation(ApiVersion.class);
                    if (optional.isPresent()) {
                        ApiVersion annotationOnClass = optional.get();
                        if (annotationOnClass != null) {
                            if (annotationOnClass.value() != null && annotationOnClass.value().length != 0) {
                                if (Arrays.asList(annotationOnClass.value()).contains(groupName)) {
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                })
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 动态创建Docket bean
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() {
        Object[] swaggerGroupList = swaggerGroupInterface.getSwaggerGroupList();
        if (null == swaggerGroupList || 0 == swaggerGroupList.length) {
            return;
        }
        // 动态注入bean， ApiSprintVersionEnum里面定义的每个枚举值会成为一个docket
        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
        if (autowireCapableBeanFactory instanceof DefaultListableBeanFactory) {
            DefaultListableBeanFactory capableBeanFactory = (DefaultListableBeanFactory) autowireCapableBeanFactory;
            for (Object group : swaggerGroupList) {
                String groupName = group.toString();
                // 要注意 "工厂名和方法名"，意思是用这个bean的指定方法创建docket
                AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                        .genericBeanDefinition()
                        .setFactoryMethodOnBean("buildDocket", "swaggerConfig")
                        .addConstructorArgValue(groupName).getBeanDefinition();
                capableBeanFactory.registerBeanDefinition(groupName, beanDefinition);
            }
        }
    }

}
